package com.digitalchina.lxnsy.activity.management;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.FertilizerVO;
import com.digitalchina.lxnsy.entity.ProductVO;
import com.digitalchina.lxnsy.entity.SeedVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/4/26 10:43
 * 修改备注：
 * ================================================
 */
public class ProductionForecastActivity extends BaseActivity {

    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.et_weight)
    EditText etWeight;
    @Bind(R.id.tv_variety)
    TextView tvVariety;
    @Bind(R.id.rb_area)
    RadioButton rbArea;
    @Bind(R.id.rb_order)
    RadioButton rbOrder;
    @Bind(R.id.rg_sort)
    RadioGroup rgSort;
    @Bind(R.id.tv_weight)
    TextView tvWeight;
    @Bind(R.id.tv_seed_dosage)
    TextView tvSeedDosage;
    @Bind(R.id.tv_type_fertilizer)
    TextView tvTypeFertilizer;
    @Bind(R.id.tv_fertilizer_dosage)
    TextView tvFertilizerDosage;
    @Bind(R.id.tv_type_pesticide)
    TextView tvTypePesticide;
    @Bind(R.id.tv_pesticide_dosage)
    TextView tvPesticideDosage;

    private OptionsPickerView pvName, pvVariety, pvTypeFertilizer, pvTypePesticide;

    private int mYear;
    private int mMonth;
    private int mDayOfMonth;


    private String varietyId = "";//种子用量标准ID
    private String FertilizerId = "";//化肥用量标准ID
    private String PesticidesId = "";//农药用量标准ID
    private String isOrderNum = "0";//0 亩总数   1 订单总量

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_production_forecast);
        setTitle("生产预测");
    }

    @Override
    public void initMember() {

        getSeedList();
        getFertilizerList();

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        tvDate.setText(mYear + "-" + (mMonth + 1) + "-" + mDayOfMonth);

    }

    @Override
    public void addListener() {

        rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (radioGroup.getCheckedRadioButtonId() == R.id.rb_area) {
                    //亩数
                    tvWeight.setText("总亩数（亩）");
                    isOrderNum = "0";
                } else {
                    //订单量
                    tvWeight.setText("总订单量（公斤）");
                    isOrderNum = "1";
                }
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0: // 保存
                        ProductVO vo = FastJsonUtil.getBean(message.obj.toString(), "productVO", ProductVO.class);
                        if (vo != null){
                            vo.setDate(tvDate.getText().toString());
                            vo.setUnit(tvWeight.getText().toString());
                            vo.setWeight(etWeight.getText().toString());
                        }

                        GotoUtil.gotoActivity(activity, ProductionForecastResultActivity.class, "ProductVO", vo);
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1: // 农作物
                        callBack(message.obj);
                        break;
                    case MSG_S_2: // 化肥农药
                        setFertilizer(message.obj);
                        break;
                }
                return false;
            }
        });
    }

    private void setFertilizer(Object object) {

        // 化肥
        final List<FertilizerVO> fertilizerList = FastJsonUtil.getListBean(object.toString(), "fertilizerList", FertilizerVO.class);
        // 农药
        final List<FertilizerVO> pesticidesList = FastJsonUtil.getListBean(object.toString(), "pesticidesList", FertilizerVO.class);


        // 化肥
        pvTypeFertilizer = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (fertilizerList == null || fertilizerList.size() == 0){
                    showToast("正在获取化肥，请稍候重试");
                    return;
                }

                tvTypeFertilizer.setText(fertilizerList.get(options1).getPickerViewText());
                tvFertilizerDosage.setText(fertilizerList.get(options1).getStandardDosage() + "kg/亩");
                FertilizerId = fertilizerList.get(options1).getId();

            }
        })
                .setTitleText("化肥")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvTypeFertilizer.setPicker(fertilizerList);

        // 农药
        pvTypePesticide = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (pesticidesList == null || pesticidesList.size() == 0){
                    showToast("正在获取农药，请稍候重试");
                    return;
                }

                tvTypePesticide.setText(pesticidesList.get(options1).getPickerViewText());
                tvPesticideDosage.setText(pesticidesList.get(options1).getStandardDosage() + pesticidesList.get(options1).getUnit());
                PesticidesId = pesticidesList.get(options1).getId();
            }
        })
                .setTitleText("农药")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvTypePesticide.setPicker(pesticidesList);

    }

    @Override
    public void callBack(Object object) {
        final List<SeedVO> voList = FastJsonUtil.getListBean(object.toString(), "list", SeedVO.class);
        final List<SeedVO> varietyList = new ArrayList<>();

        // 作物
        pvName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (voList == null || voList.size() == 0){
                    showToast("正在获取作物，请稍候重试");
                    return;
                }

                tvName.setText(voList.get(options1).getPickerViewText());
                tvVariety.setText("");
                tvSeedDosage.setText("");
                varietyId = "";
                varietyList.clear();
                for (int i = 0; i < voList.get(options1).getVariety().size(); i++) {
                    varietyList.add(voList.get(options1).getVariety().get(i));
                }
                pvVariety.setPicker(varietyList);
            }
        })
                .setTitleText("作物")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvName.setPicker(voList);

        // 品种
        pvVariety = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                tvVariety.setText(varietyList.get(options1).getPickerViewText());
                tvSeedDosage.setText(varietyList.get(options1).getStandardDosage() + "g/亩");
                varietyId = varietyList.get(options1).getId();
            }
        })
                .setTitleText("品种")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvVariety.setPicker(varietyList);


    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_name, R.id.layout_variety, R.id.layout_type_fertilizer, R.id.layout_type_pesticide, R.id.bt_result})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_name:
                if (pvName != null)
                    pvName.show();
                else {
                    showToast("正在获取作物");
                }
                break;
            case R.id.layout_variety:
                if (pvVariety != null) {
                    if (StringUtil.isTextEmpty(tvName)) {
                        showToast("请先选择作物");
                    } else
                        pvVariety.show();
                } else {
                    showToast("正在获取品种");
                }
                break;
            case R.id.layout_type_fertilizer:
                if (pvTypeFertilizer != null)
                    pvTypeFertilizer.show();
                else {
                    showToast("正在获取化肥");
                }
                break;
            case R.id.layout_type_pesticide:
                if (pvTypePesticide != null)
                    pvTypePesticide.show();
                else {
                    showToast("正在获取农药");
                }
                break;
            case R.id.bt_result: // 查看结果
                result();
                break;
        }
    }

    private void result() {


        if (StringUtil.isTextEmpty(tvName)) {
            showToast("请选择作物");
            return;
        }

        if (StringUtil.isTextEmpty(tvVariety)) {
            showToast("请选择品种");
            return;
        }

        if (StringUtil.isTextEmpty(etWeight)) {
            showToast("请填写总量");
            return;
        }

        if (StringUtil.isTextEmpty(tvTypeFertilizer)) {
            showToast("请选择化肥");
            return;
        }

        if (StringUtil.isTextEmpty(tvTypePesticide)) {
            showToast("请选择农药");
            return;
        }


        if (StringUtil.isTextEmpty(etNum)) {
            showToast("请填写用工标准");
            return;
        }

        /**
         * varietyId	种子用量标准ID
         * FertilizerId	化肥用量标准ID
         * PesticidesId	农药用量标准ID
         * worknumber	用工量
         * totalnumber	订单总数/总亩数
         * isOrderNum	（0 亩总数   1 订单总量）
         */

        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("userAccId", AdminXML.getUserAccId(activity));

        params.put("varietyId", varietyId);
        params.put("FertilizerId", FertilizerId);
        params.put("PesticidesId", PesticidesId);
        params.put("totalnumber", etWeight.getText().toString());
        params.put("worknumber", etNum.getText().toString());
        params.put("isOrderNum", isOrderNum);

        OkHttpUtil.post(activity, URL.URL_PRODUT_PREDICT, "正在查询", params, mHandler,
                MSG_S_0, MSG_F_0);

    }


    // 获取农作物品种 0不带品种  1带品种
    private void getSeedList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("type", "1");

        OkHttpUtil.post(activity, URL.URL_GET_SEED_LIST, "", params, mHandler,
                MSG_S_1, MSG_F_1);
    }

    // 农药 化肥  type = 0 化肥 type =1 农药 不传则取两种
    private void getFertilizerList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));

        OkHttpUtil.post(activity, URL.URL_GET_FERTILIZER_LIST, "", params, mHandler,
                MSG_S_2, MSG_F_2);
    }
}
